package com.zorn.core.tree;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

public class TreeNode extends HashMap<String, Object> {
	
	private static final long serialVersionUID = 8249556319042555L;

	// Constructor
	public TreeNode(String id, String parentId, String text, boolean leaf) {
		this(id, parentId, text, leaf, null);
	}

	public TreeNode(String id, String parentId, String text, boolean leaf, List<TreeNode> children) {
		this.put("id", id);
		this.put("parentId", parentId);
		this.put("text", text);
		this.put("leaf", leaf);
		this.setChildren(children);
	}

	// Overload
	public Object put(String key, Object value, boolean nullable) {
		return put(key, value, nullable, true, null);
	}

	public Object put(String key, Object value, boolean nullable, boolean blank) {
		return put(key, value, nullable, blank, null);
	}

	public Object put(String key, Object value, boolean nullable, boolean blank, Object defaults) {
		if (value == null) {
			if (nullable) return put(key, value);
		} else {
			if (StringUtils.isBlank(value.toString())) {
				if (blank) return put(key, value);
			} else return put(key, value);
		}
		if (defaults != null) return put(key, defaults);
		return null;
	}

	// Getters and Setters
	public String getId() {
		return this.get("id").toString();
	}

	public void setId(String id) {
		this.put("id", id);
	}

	public String getParentId() {
		return this.get("parentId").toString();
	}

	public void setParentId(String parentId) {
		this.put("parentId", parentId);
	}

	public String getText() {
		return this.get("parentId").toString();
	}

	public void setText(String text) {
		this.put("text", text);
	}

	public boolean isLeaf() {
		return (Boolean) this.get("leaf");
	}

	public void setLeaf(boolean leaf) {
		this.put("leaf", leaf);
	}

	@SuppressWarnings("unchecked")
	public List<TreeNode> getChildren() {
		if (this.isLeaf()) return null;
		if (this.get("children") == null) this.put("children", new ArrayList<TreeNode>());
		return (List<TreeNode>) this.get("children");
	}

	public void setChildren(List<TreeNode> children) {
		if (!this.isLeaf()) this.put("children", children == null ? new ArrayList<TreeNode>() : children);
	}

}